package com.makemoney.miniprogram.modules.users.dao.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.makemoney.miniprogram.common.consts.RedisKey;
import com.makemoney.miniprogram.common.util.IRedisService;
import com.makemoney.miniprogram.modules.users.dao.IRoleResourceDao;
import com.makemoney.miniprogram.modules.users.entity.Resources;
import com.makemoney.miniprogram.modules.users.entity.RoleResource;
import com.makemoney.miniprogram.modules.users.mapper.RoleResourceMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleResourceDaoImpl extends ServiceImpl<RoleResourceMapper, RoleResource> implements IRoleResourceDao {

    @Resource
    private IRedisService redisService;

    @Override
    public List<Resources> listByRoleKey(String roleKey) {
        String redisKey = RedisKey.ROLE + StrUtil.COLON + roleKey;
        if (redisService.isEnabled() && redisService.hasKey(redisKey)) {
            return (List<Resources>) redisService.get(redisKey);
        }
        List<Resources> resources = baseMapper.listByRoleKey(roleKey);
        if (redisService.isEnabled()) {
            redisService.set(redisKey, resources, RedisKey.ROLE_TIMEOUT);
        }
        return resources;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByResourcesIdList(List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Boolean.TRUE;
        }
        UpdateWrapper<RoleResource> wrapper = new UpdateWrapper<>();
        wrapper.lambda().in(RoleResource::getResourceId, ids);
        return this.remove(wrapper);
    }
}
